package com.allen.controller;

import com.allen.dto.TaskData;
import com.common.allen.core.utils.MyBeanUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.repository.ProcessDefinitionQuery;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @program: spring-boot-demo
 * @className ProcessController
 * @description: 参考文档 http://camunda-cn.shaochenfeng.com/user-guide/process-engine/process-engine-api/
 * @author: zp
 * @create: 2024-08-14 14:53
 * @Version 1.0
 **/
@RestController
@RequestMapping("/process")
@Api(value = "camunda接口管理", tags = "camunda工作流相关接口")
@Slf4j
public class CamundaController {

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private TaskService taskService;

    @Resource
    private HistoryService historyService;


    @GetMapping("/startProcessByKey")
    @ApiOperation(value = "通过流程key启动流程")
    public String startProcess(@Parameter(description = "流程定义key") String processKey) {
        ProcessInstance processInstance = null;
        try{
            processInstance = runtimeService.startProcessInstanceByKey(processKey);
        }catch (Exception e){
            log.error("启动流程失败",e);
        }
        return Objects.nonNull(processInstance) ? processInstance.getId() : null;
    }

    @GetMapping("/findProcess")
    @ApiOperation(value = "通过流程key查询流程信息")
    public ProcessDefinitionQuery findProcess(@Parameter(description = "流程定义key") String processKey) {
        return repositoryService.createProcessDefinitionQuery().processDefinitionKey(processKey);
    }

    @GetMapping("/getCurrentTaskList")
    @ApiOperation(value = "查询当前流程实例下任务列表")
    public List<TaskData> getCurrentTaskList(@Parameter(description = "流程实例id") String processInstanceId) {
        List<Task> list = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        return MyBeanUtils.copyProperties(list, TaskData::new);
    }

    @GetMapping("/completeTaskById")
    @ApiOperation(value = "完成当前任务")
    public void completeTaskById(@Parameter(description = "任务id") String taskId) {
         taskService.complete(taskId);
    }

}
